package com.ygqh.baby.controller.admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.foxinmy.weixin4j.type.TradeType;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.ao.Message.Type;
import com.ygqh.baby.controller.utils.DocumentHandler;
import com.ygqh.baby.excel.domain.OutOrderImportEntity;
import com.ygqh.baby.exception.YgHttpException;
import com.ygqh.baby.handler.OutOrderImportHandler;
import com.ygqh.baby.model.SaveOutOrderImportParam;
import com.ygqh.baby.model.YgOrder4ImportModel;
import com.ygqh.baby.model.YgPtSkuInfo;
import com.ygqh.baby.model.logistics;
import com.ygqh.baby.model.wdt.WdtOrderResData;
import com.ygqh.baby.model.wdt.qyb.PushOrderToWdtBatchResult;
import com.ygqh.baby.model.wdt.qyb.PushOrderToWdtResult;
import com.ygqh.baby.observer.Observable.OrderPaySuccessObservable;
import com.ygqh.baby.observer.OrderPayModel;
import com.ygqh.baby.po.*;
import com.ygqh.baby.service.*;
import com.ygqh.baby.service.ngmm.util.NgmmConfigure;
import com.ygqh.baby.service.task.WdtService;
import com.ygqh.baby.service.task.YgAsynClient;
import com.ygqh.baby.service.trustone.model.ApiResult;
import com.ygqh.baby.service.trustone.model.YgDeclareCustomsResult;
import com.ygqh.baby.service.wdtqyb.api.WdtQybPushOrderByDetailApi;
import com.ygqh.baby.service.wechat.YgWeChatService;
import com.ygqh.baby.service.wechat.message.YgTemplateMessage;
import com.ygqh.baby.service.wechat.protocol.UnifiedOrderReqData;
import com.ygqh.baby.shiro.utils.SessionUtil;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.IDAuthUtil;
import com.ygqh.baby.utils.QRCodeUtil;
import com.ygqh.baby.utils.WebUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.*;

@Controller
@RequestMapping("/admin/order")
public class OrderController extends BaseController<Object, java.lang.Long> {

    @Autowired
    private YgOrderService ygOrderService;
    @Autowired
    private FileService fileService;
    @Autowired
    private WdtService wdtService;
    @Autowired
    private YgOrderLogService ygOrderLogService;
    @Autowired
    private YgLogisticsService ygLogisticsService;
    @Autowired
    private YgOrderDetailService ygOrderDetailService;
    @Autowired
    private YgSkuService skuService;
    @Value("${micro.msg.appId}")
    private String appid;
    @Value("${wechat.pay.mchid}")
    private String mchid;
    @Value("${micro.msg.secret}")
    private String appsecret;
    @Value("${wechat.pay.notify_url}")
    private String notify_url;
    @Value("${wechat.pay.key}")
    private String key;
    @Value("${wdt.test.url}")
    private String wdt_url;
    @Autowired
    private YgOrderPaymentService orderPaymentService;
    @Autowired
    private YgFrameCodeService ygFrameCodeService;
    @Autowired
    private YgWeChatService weChatService;
    @Autowired
    private YgAsynClient wdtSyncOrderClient;
    @Autowired
    private YgOrderOperationService ygOrderOperationService;
    @Autowired
    private YgNgmmService ygNgmmService;
    @Autowired
    private ScheduleJobService scheduleJobService;
    @Autowired
    private WxSmallMessageService wxSmallMessageService;
    @Autowired
    private TrustoneService trustoneService;
    @Autowired
    private OrderPaySuccessObservable orderPaySuccessObservable;
    @Autowired
    private KidsOrderLogisticsService kidsOrderLogisticsService;

    @Value("${trustoner.supplier.id}")
    private Long TRUSTONE_SUPPLIER_ID;

    @RequestMapping("searchOrder")
    @ResponseBody
    public Map<String, Object> searchOrder(String q, QueryInfo queryInfo, Date startDate, Date endDate, OrderStatus orderStatus, Long orderId, String
            userName, String telPhone, Boolean validOrder, String appType, String sourceCode, OrderType orderType, String productName) {

        logger.info("searchOrder");
        ResultSet<YgOrder> resultSet = ygOrderService.search(queryInfo, null, orderId, null, orderStatus, startDate, endDate, q, userName, telPhone,
                validOrder ? "1" : "0", appType, sourceCode, orderType, productName);

        return resultSet.toDatatables(null);
    }

    @RequestMapping("orderDetail")
    @ResponseBody
    public YgOrder orderDetail(Long orderId) {

        return ygOrderService.findOrderDetail(orderId);
    }

    @RequestMapping("sendOrder")
    @ResponseBody
    public Message sendOrder(String orderId, String expressCompany, String expressCode, String logisticsCode, int goodAmount, Long[] detailIds) {
        YgLogistics ygLogistics = new YgLogistics();
        ygLogistics.setOrderId(orderId);
        ygLogistics.setSendTime(new Date());
        ygLogistics.setCreateTime(ygLogistics.getSendTime());
        ygLogistics.setExpressCode(expressCode);
        ygLogistics.setExpressCompany(expressCompany);
        ygLogistics.setLogisticsCode(logisticsCode);
        ygLogisticsService.save(ygLogistics);

        List<YgOrderDetail> detailList = new ArrayList<YgOrderDetail>();
        for (Long id : detailIds) {
            YgOrderDetail detail = new YgOrderDetail();
            detail.setDetailStatus(OrderDetailStatus.WaitingSign);
            detail.setSendMark(expressCode);
            detail.setId(id);
            detailList.add(detail);
        }
        ygOrderDetailService.updateDetailSendBatch(detailList);

        YgOrder ygOrder = ygOrderService.findOrderDetailByOrderId(Long.valueOf(orderId));
        ygOrder.setOrderId(Long.valueOf(orderId));
        ygOrder.setSendTime(ygLogistics.getSendTime());
        ygOrder.setOrderStatus(OrderStatus.WaitingSign);
        if (ygOrder.getExpressCode() == null) {
            // 第一次发货
            if (ygOrder.getOrderDetail().size() > goodAmount) {
                // 部分发货
                ygOrder.setExpressCode("true");
                ygOrder.setLogisticsCode(goodAmount + "");
            } else {
                ygOrder.setExpressCode("false");
                ygOrder.setLogisticsCode(goodAmount + "");
            }
        } else {
            // 不是第一次发货
            int amount = Integer.parseInt(ygOrder.getLogisticsCode() == null ? "0" : ygOrder.getLogisticsCode());
            ygOrder.setLogisticsCode((amount + goodAmount) + "");
        }

        ygOrderService.updateByOrderId(ygOrder);
//        appMessageService.sendOrderDeliveryNotice(orderId.toString(), ygOrder.getUserId().toString(), "order", "发货啦");

        scheduleJobService.addBalanceJob(ygOrder.getOrderId(), ygOrder.getSendTime(), "sendOrder");

        // 判断是否为年糕妈妈订单
        if (ygOrder.getSupplierId().equals(NgmmConfigure.DEFAULT_SUPPLIER_ID)) {
            ygNgmmService.updateNgmmExpress(orderId, logisticsCode, expressCode);
        }

        kidsOrderLogisticsService.addBatchByYgLogistics(Collections.singletonList(ygLogistics));

        if (StringUtils.isNotBlank(ygOrder.getPlatformNo())) {
            YgTemplateMessage tplMessage = wxSmallMessageService.getOrderSendMsgByPlatform(ygOrder, expressCompany, expressCode);
            wxSmallMessageService.sendTmplMsg(tplMessage);
        }
        return SUCCESS_MESSAGE;
    }

    @RequestMapping("completeOrder")
    @ResponseBody
    public Message completeOrder(Long id) {
        YgOrder order = new YgOrder();
        order.setId(id);
        order.setConfirmReceiveTime(new Date());
        order.setOrderStatus(OrderStatus.TradeSuccess);
        ygOrderService.update(order);
        return SUCCESS_MESSAGE;

    }

    @RequestMapping("updateExpressPrice")
    @ResponseBody
    public Message updateExpressPrice(Long orderId, BigDecimal expressPrice) {
        AdminUser adminUser = getSession();
        YgOrder ygOrder = ygOrderService.findByOrderId(orderId);
        BigDecimal old = ygOrder.getExpressPrice();
        BigDecimal totalPrice = ygOrder.getTotalPrice().subtract(old).add(expressPrice);
        ygOrder.setTotalPrice(totalPrice);
        ygOrder.setExpressPrice(expressPrice);
        ygOrderService.update(ygOrder);
        ygOrderLogService.addOrderLog(ygOrder.getOrderId(), ygOrder.getOrderStatus(), adminUser.getUsername(), "修改订单运费，原运费：" + old + ",新运费：" + expressPrice);
        return SUCCESS_MESSAGE;

    }

    @RequestMapping("updateUserRemark")
    @ResponseBody
    public Message updateUserRemark(Long orderId, String userRemark) {
        YgOrder order = new YgOrder();
        order.setOrderId(orderId);
        order.setUserRemark(userRemark);
        int i = ygOrderService.updateByOrderId(order);
        return Message.success(i);

    }

    @RequestMapping("syncOrder")
    @ResponseBody
    public Message syncOrder(Long orderId) {
        AdminUser adminUser = getSession();
        String content = "";
        YgOrder ygOrder = ygOrderService.findOrderDetailByOrderId(orderId);
        if (ygOrder.getOrderStatus().equals(OrderStatus.WaitingPay) || ygOrder.getOrderStatus().equals(OrderStatus.TradeClosed)) {
            return ERROR_MESSAGE;
        }
        System.err.println(wdt_url);
        ygOrderLogService.addOrderLog(orderId, ygOrder.getOrderStatus(), adminUser.getUsername(), adminUser.getUsername() + "手动同步订单" + ";旺店通单号：" + ygOrder
                .getWdtOrderCode());
        // 本地订单同步到旺店通
        if (ygOrder.getWdtOrderCode() == null) {
            List<Long> orderIds = new ArrayList<Long>();
            orderIds.add(orderId);
            // Message msg = wdtService.createOrderByOrderIds(orderIds);
            wdtSyncOrderClient.syncQybOrder(orderIds);

            return Message.success(null);
        } else {
            // 旺店通订单往本地同步 1.发货状态；2.是否取消
            WdtOrderResData result = (WdtOrderResData) wdtService.QueryTradeByNO(ygOrder.getWdtOrderCode());
            int size = result.getDetailList().getDetail().size();
            if (result != null) {
                if (result.getResultCode() > 0) {
                    return Message.error(result.getResultMsg(), result);
                }
                // 发货
                if (result.getTradeStatus().equals(WdtTradeStatus.over_trade.name())) {
                    // 本地订单为待发货状态时，同步发货数据到本地
                    if (ygOrder.getOrderStatus().equals(OrderStatus.WaitingSend)) {
                        ygOrder.setWdtOrderCode(result.getTradeNO());
                        ygOrder.setOrderStatus(OrderStatus.WaitingSign);
                        ygOrder.setSendTime(result.getSndTime());
                        if (ygOrder.getExpressCode() == null) {
                            // 第一次发货
                            if (ygOrder.getOrderDetail().size() > size) {
                                // 部分发货
                                ygOrder.setExpressCode("true");
                                ygOrder.setLogisticsCode(size + "");
                            } else {
                                ygOrder.setExpressCode("false");
                                ygOrder.setLogisticsCode(size + "");
                            }
                        } else {
                            // 不是第一次发货
                            int amount = Integer.parseInt(ygOrder.getLogisticsCode() == null ? "0" : ygOrder.getLogisticsCode());
                            ygOrder.setLogisticsCode((amount + size) + "");
                        }

                        ygOrderService.update(ygOrder);

                        YgLogistics logistics = new YgLogistics();
                        logistics.setOrderId(orderId.toString());
                        logistics.setSendTime(new Date());
                        logistics.setCreateTime(new Date());
                        logistics.setExpressCode(result.getPostID());
                        logistics.setExpressCompany(result.getLogisticsName());
                        logistics.setLogisticsCode(result.getLogisticsCode());
                        ygLogisticsService.save(logistics);

                        ygOrderLogService.addOrderLog(ygOrder.getOrderId(), OrderStatus.WaitingSign, adminUser.getUsername(), "运营后台，同步订单发货状态");

                        content = "订单同步物流信息成功";
                    }

                }
                // 取消
                if (result.getTradeStatus().equals(WdtTradeStatus.cancel_trade.name())) {
                    // 本地订单没有取消时，取消本地订单
                    if (!ygOrder.getOrderStatus().equals(OrderStatus.TradeClosed)) {
                        ygOrder.setCancelReason("系统同步旺店通订单。订单被取消。");
                        ygOrder.setCancelTime(result.getLastModifyTime());
                        ygOrder.setReturnOrderId(Long.parseLong(ygOrder.getOrderId() + "1"));
                        ygOrder.setOrderStatus(OrderStatus.TradeClosed);
                        ygOrderService.updateByOrderId(ygOrder);
                        ygOrderLogService.addOrderLog(ygOrder.getOrderId(), OrderStatus.TradeClosed, adminUser.getUsername(), "运营后台，同步订单，订单被取消");
                        content = "订单被取消";
                    }
                }

                List<String> orderNoList = wdtService.findWdtOrderNoList();

                // 不存在
                if (!orderNoList.contains(result.getTradeNO())) {
                    wdtService.saveWdtOrder(result);
                }
            } else {
                return Message.error("接口异常，请查询配置是否正确", orderId);
            }
        }

        return Message.success(content, null);

    }

    @RequestMapping("exportOrder")
    public void exportOrder(Date startDate, Date endDate, String userName, String telPhone, String sourceCode, String q, String orderStatus, Boolean
            validOrder, String productName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        endDate = DateConvertUtils.addDay(endDate, 1);

        List<Map<String, Object>> list = ygOrderService.getOrderReport(startDate, endDate, userName, sourceCode, q, orderStatus, telPhone, validOrder,
                productName);

        byte[] bytes = fileService.downloadFromOss("template/productorderlist.xlsx");
        List<Map<String, Object>> dataMaps = new ArrayList<Map<String, Object>>();
        Map<String, Object> dataMap = new HashMap<String, Object>();

        dataMap.put("resultSet", list);
        dataMaps.add(dataMap);
        DocumentHandler.DownloadExcel(bytes, "订单统计.xlsx", dataMap, request, response);
    }

    @RequestMapping("payOrder")
    @ResponseBody
    public Message payOrder(Long orderId, BigDecimal totalPrice, PayType payType, HttpServletRequest request, HttpServletResponse response) {
        ygOrderService.splitOrderV2(orderId, totalPrice, payType);
        orderPaySuccessObservable.paySuccess(new OrderPayModel(orderId, totalPrice, payType, orderId.toString()));
        return SUCCESS_MESSAGE;
    }

    @RequestMapping("qrPayOrder")
    @ResponseBody
    public Message qrPayOrder(String state, HttpServletRequest request, HttpServletResponse response) {

        Message msg = null;
        String ipAddress = WebUtils.getIpAddr(request);
        System.out.println("客户端ip：" + ipAddress);
        String[] split = ipAddress.split(",");
        ipAddress = split[0];
        System.out.println("客户端ip：" + ipAddress);
        System.out.println("微信支付回调地址：" + notify_url);
        String[] str = state.split("-");
        String coderUrl = "";
        // 判断该订单是否已经支付过
        YgOrder ygOrder = ygOrderService.findByOrderId(Long.parseLong(str[0]));
        if (ygOrder != null && !ygOrder.getOrderStatus().equals(OrderStatus.WaitingPay)) {
            return SUCCESS_MESSAGE;
        }
        try {
            // 生成支付流水
            Long paymentCode = ygFrameCodeService.getFrameCode(CodeType.OrderPM, new Date());
            orderPaymentService.addPaymentRecord(str[0], new BigDecimal(str[1]), paymentCode.toString(), PayType.WeChat, AppType.WeChat);

            UnifiedOrderReqData reqData = new UnifiedOrderReqData.UnifiedOrderReqDataBuilder(appid, mchid, "壹果订单", paymentCode.toString(), new BigDecimal
                    (str[1]).multiply(new BigDecimal(100)).intValue(), ipAddress, notify_url, TradeType.NATIVE.name()).setProduct_id("000").build();
            msg = weChatService.UnifiedOrderNATIVE(reqData);
            coderUrl = (String) msg.getExtra();
            coderUrl = this.getPayCode(coderUrl, paymentCode, request);

        } catch (Exception e) {
            ygOrderLogService.addOrderLog(Long.parseLong(str[0]), OrderStatus.WaitingPay, "15911009019", "发起微信支付失败" + e.getMessage());
            e.printStackTrace();
            return ERROR_MESSAGE;
        }

        return new Message(Type.success, coderUrl);
    }

    private String getPayCode(String coderUrl, Long paymentCode, HttpServletRequest request) {
        String path = request.getRealPath("/");
        String realPath = path + "/PayCodeImage";
        String fileName = "payCode" + paymentCode + ".jpg";
        String qrcodeUrl = "";
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            realPath = QRCodeUtil.encode(coderUrl, realPath, fileName);
            if (!StringUtil.isBlank(realPath)) {
                File file = new File(realPath);
                String str = file.toString();

                String ext = fileName.split("\\.")[1];
                String imageTmpUrl = request.getSession().getServletContext().getRealPath("/") + UUID.randomUUID().toString() + "" + "." + ext;
                GenerateImage(str, imageTmpUrl);
                File file1 = new File(imageTmpUrl);
                System.out.println(file1.getAbsolutePath());
                System.out.println(file1.getName());
                qrcodeUrl = fileService.uploadImage(file, new FileType[]{FileType.PayCode}, ext, true, request);

            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return qrcodeUrl;

    }

    public static boolean GenerateImage(String imgStr, String imgFilePath) { // 对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null || null == imgFilePath) // 图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b, 0, b.length);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @RequestMapping("exportOrderLogistics")
    public void exportOrderLogistics(Date startDate, Date endDate, String userName, String telPhone, String sourceCode, String q, String orderStatus, Boolean
            validOrder, HttpServletRequest request, HttpServletResponse response) throws IOException {
        endDate = DateConvertUtils.addDay(endDate, 1);
        List<Map<String, Object>> list = ygOrderService.getOrderLogisticsReport(startDate, endDate, userName, sourceCode, q, orderStatus, telPhone, validOrder);
        byte[] bytes = fileService.downloadFromOss("template/orderlogisticslist.xls");
        List<Map<String, Object>> dataMaps = new ArrayList<Map<String, Object>>();
        Map<String, Object> dataMap = new HashMap<String, Object>();

        dataMap.put("resultSet", list);
        dataMaps.add(dataMap);
        DocumentHandler.DownloadExcel(bytes, "订单物流统计.xls", dataMap, request, response);
    }

    @RequestMapping("exportLogisticsCode")
    public void exportLogisticsCode(String expCode, String logisticsCode, HttpServletRequest request, HttpServletResponse response) throws IOException,
            InterruptedException, ExecutionException {

        String[] arr = logisticsCode.split("\r\n");
        List<logistics> newlist = new ArrayList<logistics>();

        ExecutorService sendExecutor = Executors.newFixedThreadPool(3);
        CompletionService<logistics> completion = new ExecutorCompletionService<logistics>(sendExecutor);
        List<logistics> callSendList = new ArrayList<logistics>(arr.length);
        for (String s : arr) {
            Future<logistics> futureSend = completion.submit(new Callable<logistics>() {
                @Override
                public logistics call() throws Exception {
                    Message msg = null;
                    msg = ygOrderService.getLogisticsInfo(expCode, s.toString());
                    ArrayList list = (ArrayList) msg.getExtra();
                    Map<String, String> map = (Map<String, String>) list.get(0);
                    logistics lo = new logistics();
                    lo.setExpNo(s.toString());
                    lo.setAcceptTime(map.get("AcceptTime"));
                    return lo;
                }
            });
            callSendList.add(futureSend.get());
        }
        // 关闭启动线程,不再接受新的任务
        sendExecutor.shutdown();
        byte[] bytes = fileService.downloadFromOss("template/logisticsCode.xls");
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("resultSet", callSendList);
        DocumentHandler.DownloadExcel(bytes, "物流单统计.xls", dataMap, request, response);

    }

    /**
     * 该方法不建议使用,请使用 uploadOrderExcel
     */
    @RequestMapping("loadOrderExcel")
    @ResponseBody
    public Message loadOrderExcel(@RequestParam("uploadFile") MultipartFile uploadFile) throws
            IOException {

        InputStream is = uploadFile.getInputStream();
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);

        Map map = new HashMap();
        List<YgOrder4ImportModel> orderList = new ArrayList<>();
        try {
            // Read the Sheet
            for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
                XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
                if (xssfSheet == null) {
                    continue;
                }

                // Read the Row
                for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
                    XSSFRow xssfRow = xssfSheet.getRow(rowNum);
                    if (xssfRow != null) {

                        XSSFCell orderId = xssfRow.getCell(0);
                        XSSFCell receiver = xssfRow.getCell(1);
                        XSSFCell telPhone = xssfRow.getCell(2);
                        XSSFCell provinceName = xssfRow.getCell(3);
                        XSSFCell cityName = xssfRow.getCell(4);
                        XSSFCell areaName = xssfRow.getCell(5);
                        XSSFCell address = xssfRow.getCell(6);
                        XSSFCell skuCode = xssfRow.getCell(7);
                        XSSFCell quantity = xssfRow.getCell(8);
                        XSSFCell salesPrice = xssfRow.getCell(9);
                        XSSFCell sourceCode = xssfRow.getCell(10);
                        YgOrder4ImportModel model = new YgOrder4ImportModel();
                        model.setOrderId(Long.valueOf(orderId.toString().trim()));
                        model.setSkuCode(skuCode.toString().trim());
                        model.setQuantity(Long.valueOf(getValue(quantity, "0")));
                        model.setReceiver(receiver.toString());
                        model.setTelPhone(telPhone.toString().trim());
                        model.setProvinceName(provinceName.toString());
                        model.setCityName(cityName.toString());
                        model.setAreaName(areaName.toString());
                        model.setAddress(address.toString());
                        model.setSourceCode(sourceCode.toString());
                        model.setUserName(telPhone.toString().trim());
                        model.setSalesPrice(new BigDecimal(getValue(salesPrice, "0.00")));
                        checkData(model);
                        YgOrder4ImportModel dbModel = skuService.findOrder4ImportModel(model.getSkuCode());
                        if (dbModel == null) {
                            String r = model.getRemark();
                            model.setRemark(r + "SKU不存在;");
                        } else {
                            model.setProductName(dbModel.getProductName());
                            model.setSizeName(dbModel.getSizeName());
                            model.setSalesPrice(dbModel.getSalesPrice());
                        }
                        orderList.add(model);

                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(orderList);
        }

        return Message.success(orderList);
    }

    private void checkData(YgOrder4ImportModel model) {
        StringBuilder remark = new StringBuilder();
        if (model.getSkuCode() == null) {
            remark.append("请填写有效的SKU;");
        }
        if (model.getQuantity() == null || model.getQuantity().intValue() <= 0) {
            remark.append("请填写有效的购买数量;");
        }
        if (model.getReceiver() == null) {
            remark.append("请填写有效的收货人姓名;");
        }
        if (model.getTelPhone() == null || model.getTelPhone().length() != 11) {
            remark.append("请填写有效的收货人手机号;");
        }
        if (model.getProvinceName() == null || model.getCityName() == null || model.getAreaName() == null) {
            remark.append("请填写有效的省市区;");
        }
        if (model.getAddress() == null) {
            remark.append("请填写有效的收货地址;");
        }

        model.setRemark(remark.toString());
    }

    /**
     * 得到Excel表中的值
     *
     * @param hssfCell Excel中的每一个格子
     * @return Excel中每一个格子中的值
     */
    @SuppressWarnings("static-access")
    private String getValue(XSSFCell hssfCell, String type) {
        if (hssfCell == null) return null;
        if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
            // 返回布尔类型的值
            return String.valueOf(hssfCell.getBooleanCellValue());
        } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
            DecimalFormat df = new DecimalFormat(type);
            String str = df.format(hssfCell.getNumericCellValue());
            // 返回数值类型的值
            return str;
        } else {
            // 返回字符串类型的值
            return String.valueOf(hssfCell.getStringCellValue());
        }
    }

    /**
     * 该方法不建议使用,请使用 saveOutOrderByImport
     */
    @RequestMapping("saveImportOrder")
    @ResponseBody
    Message saveImportOrder(String orderList) {
        List<YgOrder4ImportModel> order4ImportModels = JSON.parseObject(orderList, new TypeReference<List<YgOrder4ImportModel>>() {
        });
        Long userId = 38L;

        if (order4ImportModels.get(0).getSourceCode().equals("wxbtlmm1128")) {
            userId = 39L;
        }
        return ygOrderService.saveImportThirdOrder(order4ImportModels, userId);
    }

    @RequestMapping("exportProductOrder")
    public void exportProductOrder(String productName, OrderStatus orderStatus, HttpServletRequest request, HttpServletResponse response) {

        List<Map<String, Object>> list = ygOrderService.selectOrderByProductName(productName);
        byte[] bytes = fileService.downloadFromOss("template/productorderlist.xlsx");
        List<Map<String, Object>> dataMaps = new ArrayList<Map<String, Object>>();
        Map<String, Object> dataMap = new HashMap<String, Object>();

        dataMap.put("resultSet", list);
        dataMaps.add(dataMap);
        DocumentHandler.DownloadExcel(bytes, "商品订单.xlsx", dataMap, request, response);
    }

    @RequestMapping("isModified")
    @ResponseBody
    Boolean isModified(Long orderId) {
        List<YgOrderOperation> list = ygOrderOperationService.findByOrderId(orderId, OrderOperation.MofidyDetail);
        if (CollectionUtils.isEmpty(list)) return false;
        return true;

    }

    @RequestMapping("modifyDetail")
    @ResponseBody
    Message modifyDetail(Long detailId, Long userId, String skuInfos) {
        AdminUser user = SessionUtil.getCurrentUser();
        List<YgPtSkuInfo> skuList = JSON.parseObject(skuInfos, new TypeReference<List<YgPtSkuInfo>>() {
        });
        return ygOrderDetailService.modifyDetail(detailId, userId, skuList, user.getTrueName());
    }

    @RequestMapping("updateAddress")
    @ResponseBody
    public Message updateAddress(String order) {
        YgOrder ygOrder = JSON.parseObject(order, YgOrder.class);
        ygOrderService.update(ygOrder);
        return SUCCESS_MESSAGE;

    }

    @RequestMapping("selectNoSendOrderList")
    @ResponseBody
    public Map<String, Object> selectNoSendOrderList(QueryInfo queryInfo, Date startDate, Date endDate) {
        ResultSet<Map<String, Object>> list = ygOrderService.selectNoSendOrderList(queryInfo, startDate, endDate);
        return list.toDatatables(null);

    }

    @RequestMapping("selectNoSendOrderDetail")
    @ResponseBody
    public Map<String, Object> selectNoSendOrderDetail(QueryInfo queryInfo, Long supplierId, Date startDate, Date endDate) {
        ResultSet<Map<String, Object>> list = ygOrderService.selectNoSendOrderDetail(queryInfo, supplierId, startDate, endDate);
        return list.toDatatables(null);

    }

    /**
     * 导出销售的产品信息
     */
    @RequestMapping("exportOrderByProductId")
    @ResponseBody
    public void exportOrderByProductId(Date startDate, Date endDate, String q,
                                       @RequestParam(defaultValue = "M000") String platformNo,
                                       HttpServletRequest request, HttpServletResponse response) {
        List<Map<String, Object>> list = ygOrderDetailService.exportOrderByProductId(startDate, endDate, q, platformNo);
        byte[] bytes = fileService.downloadFromOss("template/product_sales_orderlist.xlsx");
        List<Map<String, Object>> dataMaps = new ArrayList<Map<String, Object>>();
        Map<String, Object> dataMap = new HashMap<String, Object>();

        dataMap.put("resultSet", list);
        dataMaps.add(dataMap);
        DocumentHandler.DownloadExcel(bytes, "商品销售统计.xlsx", dataMap, request, response);


    }

    /**
     * 根据商品Id更新订单明细中的商家ID
     */
    @RequestMapping("updateOrderSupplierId")
    @ResponseBody
    public Message updateOrderSupplierId(Long[] productIds, Long supplierId) {

        return ygOrderDetailService.updateDetailSupplierId(productIds, supplierId);

    }

    @RequestMapping(value = "cancelTrustoneOrder", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity cancelTrustoneOrder(String orderId, String reason) throws YgHttpException {
        ApiResult cancelorder = trustoneService.cancelorder(orderId, reason);
        return ResponseEntity.success(cancelorder);
    }

    @RequestMapping(value = "customDelarereDeclareByWx", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity customDelarereDeclareByWx(AppType appType, String orderPayCode, String transactionId) {
        YgDeclareCustomsResult ygDeclareCustomsResult = trustoneService.customDelarereModifyByWx(orderPayCode, transactionId, appType);
        return ResponseEntity.success(ygDeclareCustomsResult);
    }

    @Autowired
    private OutOrderImportHandler outOrderImportHandler;


    @RequestMapping("uploadOrderExcel")
    @ResponseBody
    public Message uploadOrderExcel(@RequestParam("uploadFile") MultipartFile uploadFile) {
        List<OutOrderImportEntity> outOrderImportEntities = outOrderImportHandler.loadOrderExcel(uploadFile);
        return Message.success(outOrderImportEntities);
    }

    @RequestMapping("saveOutOrderByImport")
    @ResponseBody
    public Message saveOutOrderByImport(@RequestBody SaveOutOrderImportParam param) {
        return outOrderImportHandler.saveOutOrder(param);
    }

    @RequestMapping("exportSelectNoSendOrderDetail")
    @ResponseBody
    public void exportSelectNoSendOrderDetail(String supplierName, Long supplierId, Date startDate, Date endDate, HttpServletRequest request, HttpServletResponse response) {

        List<Map<String, Object>> list = ygOrderService.getOrderDetailBySupplier(null, startDate, endDate, OrderStatus.WaitingSend, null, supplierId);
        if (supplierId.compareTo(TRUSTONE_SUPPLIER_ID) == 0) {
            list.forEach(map -> {
                map.put("identityNo", IDAuthUtil.decryptIdNo(map.get("identityNo").toString()));
            });
        }

        byte[] bytes = fileService.downloadFromOss("template/supplierorderlist.xlsx");
        List<Map<String, Object>> dataMaps = new ArrayList<Map<String, Object>>();
        Map<String, Object> dataMap = new HashMap<String, Object>();

        dataMap.put("resultSet", list);
        dataMaps.add(dataMap);
        String fileName = String.format("%s待发货(%tF至%tF).xlsx", supplierName, startDate, endDate);
        DocumentHandler.DownloadExcel(bytes, fileName, dataMap, request, response);


    }

    @Autowired
    private WdtQybPushOrderByDetailApi pushOrderToWdtByDetailHandler;

    @RequestMapping(method = RequestMethod.POST, value = "syncOrderToWdt")
    @ResponseBody
    public Message syncOrderToWdt(Long[] orderIds, @RequestParam(defaultValue = "Valid") DataStatus dataStatus) {
        if (orderIds == null || orderIds.length == 0) {
            return Message.error("orderIds is null.", orderIds);
        }
        List<YgOrder> orderList = new ArrayList<>(orderIds.length);
        for (Long orderId : orderIds) {
            YgOrder order = ygOrderService.findOrderDetailByOrderId(orderId, dataStatus);
            if (order != null) {
                orderList.add(order);
            }
        }
        ResponseEntity responseEntity = pushOrderToWdtByDetailHandler.pushOrderToWdtBatch(null, orderList);
        PushOrderToWdtBatchResult pushOrderToWdtBatchResult = (PushOrderToWdtBatchResult) responseEntity.getData();
        ygOrderService.updateWdtCodeBatch(pushOrderToWdtBatchResult.getSuccessList());
        return Message.success(responseEntity.getData());
    }

    @RequestMapping("pushUnSendOrderToWdtBySupplierId")
    @ResponseBody
    public Message pushUnSendOrderToWdt(@RequestParam Long supplierId) {
        ResponseEntity responseEntity = pushOrderToWdtByDetailHandler.pushOrderToWdtBySupplier(supplierId, null);
        PushOrderToWdtBatchResult pushOrderToWdtBatchResult = (PushOrderToWdtBatchResult) responseEntity.getData();
        ygOrderService.updateWdtCodeBatch(pushOrderToWdtBatchResult.getSuccessList());
        return responseEntity.converter();
    }

    /**
     * 按本地订单取消旺店通订单（一个订单多次推送，都会取消（旺店通未审核的订单））
     *
     * @param orderIds 本地订单id
     * @return Message
     */
    @RequestMapping("cancelWdtOrder")
    @ResponseBody
    public Message cancelWdtOrder(@RequestParam Long[] orderIds) {
        List<Object> errorList = null;
        for (Long orderId : orderIds) {
            ResponseEntity responseEntity = pushOrderToWdtByDetailHandler.cancelWdtOrder(orderId);
            if (!responseEntity.isSuccess()) {
                if (org.apache.commons.collections4.CollectionUtils.isEmpty(errorList)) {
                    errorList = new ArrayList<>();
                }
                errorList.add(responseEntity.getData());
            }
        }
        if (errorList == null) {
            return Message.success(null);
        }
        return Message.error(errorList);
    }

    /**
     * 指定第几次推送（即 指定旺店通原始单号）
     *
     * @param orderIds   待推送订单，只推送壹果发货的商品
     * @param startTimes 第几次推送
     * @return Message 异常时返回推送异常的订单（推送旺店通数据问题，非接口异常）
     */
    @RequestMapping("pushWdtOrderByStartTimes")
    @ResponseBody
    public Message pushWdtOrderByStartTimes(@RequestParam Long[] orderIds, int startTimes) {
        List<Object> errorList = null;
        for (Long orderId : orderIds) {
            ResponseEntity responseEntity = pushOrderToWdtByDetailHandler.pushWdtOrderByStartTimes(orderId, startTimes);
            if (!responseEntity.isSuccess()) {
                if (org.apache.commons.collections4.CollectionUtils.isEmpty(errorList)) {
                    errorList = new ArrayList<>();
                }
                errorList.add(responseEntity.getData());
            } else {
                PushOrderToWdtResult data = (PushOrderToWdtResult) responseEntity.getData();
                ygOrderService.updateWdtCode(data);
            }
        }
        if (errorList == null) {
            return Message.success(null);
        }
        return Message.error(errorList);
    }

}
